#include "loginwindow.h"
#include "ui_loginwindow.h"
#include "homepage.h"

LoginWindow::LoginWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LoginWindow)
{
    ui->setupUi(this);
    setWindowFlags(Qt::FramelessWindowHint);//去除标题栏
    this->setFixedSize(800,600);
    //connectDB();


    //初始化密码
    eyeOpenIcon = QIcon(":/new/prefix1/img/eye.png");
    eyecloseIcon = QIcon(":/new/prefix1/img/close.png");
    displayPasswordAction = new QAction(eyecloseIcon,"",this);
    ui->passwordlineEdit->addAction(displayPasswordAction,QLineEdit::TrailingPosition);
    connect(displayPasswordAction,&QAction::triggered,this,&LoginWindow::togglePasswordVisibility);
    ui->passwordlineEdit->setEchoMode(QLineEdit::Password);

   // togglePasswordVisibility();
    // ui->passwordlineEdit->addAction(displayPasswordAction,QLineEdit::TrailingPosition);

}

LoginWindow::~LoginWindow()
{
    delete ui;
}

void LoginWindow::initLoginWindow()
{
    ui->label_4->setStyleSheet("QTabWidget::pane { border: 0; }");
}

void LoginWindow::connectDB()
{
    //添加数据库
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setHostName("127.0.0.1");
    db.setDatabaseName("../Qtobject/data.db");
    db.open();
    if(!db.open())
    {
        QMessageBox::critical(nullptr,"错误","数据库连接失败");
        return;
    }
}

void LoginWindow::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {  // 判断是否为左键按下
            mousePressed = true;  // 标记鼠标已按下
            mousePoint = event->globalPos() - this->pos();  // 计算鼠标相对窗口的位置
            event->accept();  // 接受事件，不再传递
    }
}

void LoginWindow::mouseMoveEvent(QMouseEvent *event)
{
    if (mousePressed && (event->buttons() && Qt::LeftButton)) {  // 判断是否为左键按下并且正在移动
            this->move(event->globalPos() - mousePoint);  // 根据鼠标移动的距离移动窗口
            event->accept();  // 接受事件，不再传递
        }

}

void LoginWindow::mouseReleaseEvent(QMouseEvent *event)
{
    mousePressed = false;  // 重置鼠标按下状态
       event->accept();  // 接受事件，不再传递
}


void LoginWindow::on_remembercheckBox_clicked()
{
   // QSettings settings("username","password");
   // settings.setValue("username",usernamelineEdit.text());
    //settings.setValue("password",passwordlineEdit);
    ui->remembercheckBox->setChecked(true);//勾选记住用户名密码
    loadPasswords();
}

void LoginWindow::on_loginpushButton_clicked()
{
    QString username = ui->usernamelineEdit->text();
    QString password = ui->passwordlineEdit->text();
    QString sql = "select *from userinfo;";
    QSqlQuery query;
    query.prepare(sql);
    query.exec();

       bool login = false;  //设置标志变量

       while(query.next())
       {
           if(query.value(0) ==  username && query.value(1) ==password)
           {
               login = true;  // 找到匹配信息，设置标志变量为 true

               break;  // 退出循环
           }
       }
       if(!login)   // 循环结束后，根据标志变量的值判断是否弹出提示框
       {
           QMessageBox::information(this,"登录失败：","请检查账号或密码是否正确！",QMessageBox::Ok);
       }else
       {
           HomePage *home = new HomePage;
           home->show();
       }

}
//注册按钮
void LoginWindow::on_enrollpushButton_clicked()
{

   enrollWindow *enl = new enrollWindow();
   connect(enl,&enrollWindow::returnloginwindow,[=](){
      show();
   });
   enl->setAttribute(Qt::WA_DeleteOnClose);
   enl->show();
   close();
}
//关闭按钮
void LoginWindow::on_closepushButton_clicked()
{
    close();

}

void LoginWindow::togglePasswordVisibility()
{

   static bool m_bVisible = false;  //隐藏、显示标志
    if (m_bVisible)  //设置为隐藏密码
    {
        ui->passwordlineEdit->setEchoMode(QLineEdit::Password);
        displayPasswordAction->setIcon(eyecloseIcon);
    }
    else  //设置为显示密码
    {
        ui->passwordlineEdit->setEchoMode(QLineEdit::Normal);
        displayPasswordAction->setIcon(eyeOpenIcon);
    }

   m_bVisible = !m_bVisible;
}

//加载上一次登录账号密码
void LoginWindow::loadLastLoginInfo()
{
    QFile file("user.csv");
       if (file.open(QIODevice::ReadOnly | QIODevice::Text))
       {
           QTextStream in(&file);
           QString lastUsername;
           while (!in.atEnd())
           {
               QString line = in.readLine();
               QStringList parts = line.split(',');
               if (parts.size() == 2)
               {
                   savedPasswords[parts[0]] = parts[1];
                   lastUsername = parts[0];  // 假设最后一行是上次登录的用户名
               }
           }
           file.close();

           if (!lastUsername.isEmpty())
           {
               ui->usernamelineEdit->setText(lastUsername);
           }

          // if (ui->loginCheckBox->isChecked())
           //{
               //on_loginCheckBox_stateChanged(Qt::Checked);
           //}
       }
}
//更新账号输入框
void LoginWindow::on_usernamelineEdit_textChanged(const QString &text)
{
    if (ui->passwordlineEdit && savedPasswords.contains(text))
       {
           ui->passwordlineEdit->setText(savedPasswords[text]);
       }
       else
       {
           ui->passwordlineEdit->clear();
       }


}


//将密码加载到csv文件中
void LoginWindow::savePassword(const QString &username, const QString &password)
{
    QFile file("user.csv");
       if (file.open(QIODevice::Append | QIODevice::Text))
       {
           QTextStream out(&file);
           out << username << "," << password << "\n";
           file.close();
       }
       else
          {
              QMessageBox::warning(this, "错误", "无法打开文件以保存密码！");
          }

}

//将密码保存到csv文件中
void LoginWindow::loadPasswords()
{

    QFile file("user.csv");
      if (file.open(QIODevice::ReadOnly | QIODevice::Text))
      {
          QTextStream in(&file);
          while (!in.atEnd())
          {
              QString line = in.readLine();
              QStringList parts = line.split(',');
              if (parts.size() == 2)
              {
                  savedPasswords[parts[0]] = parts[1];
              }
          }
          file.close();
   }
}


void LoginWindow::on_maxpushButton_clicked()
{
     showMinimized();
}
